package ${tempValues.package_this_file};

import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.apache.dubbo.rpc.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DubboShutdowner {
    private static Logger logger = LoggerFactory.getLogger(DubboShutdowner.class);

    /**
    * 用于应用下线前停止dubbo服务
    *
    * @return
    */
    public static String stopDubbo() {
        logger.info("接收到dubbo下线指令");
        // destroy all registers
        AbstractRegistryFactory.destroyAll();
        // destroy all protocols
        destroyProtocols();
        // 默认success
        return "success";
    }

    private static void destroyProtocols() {
        ExtensionLoader<Protocol> loader = ExtensionLoader.getExtensionLoader(Protocol.class);
        loader.getLoadedExtensions().stream().forEach(protocolName -> {
            try {
                Protocol protocol = loader.getLoadedExtension(protocolName);
                if (protocol != null) {
                    protocol.destroy();
                }
            } catch (Exception e) {
                logger.warn("destroy protocol failure, for {}", e.getMessage(), e);
            }
        });
    }
}